import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:palette_generator/palette_generator.dart';

import 'package:flutter_popcorntime/models/json/video_data_json.dart';
import 'package:flutter_popcorntime/config/application.dart';
import 'package:flutter_popcorntime/utils/color_util.dart';

import 'package:flutter_popcorntime/widgets/cached_image_widget.dart';
import 'package:flutter_popcorntime/widgets/icon_text_button.dart';
import 'package:flutter_popcorntime/widgets/rating_chart_widget.dart';
import 'package:flutter_popcorntime/widgets/rating_star_widget.dart';

class VideoDetailPage extends StatefulWidget {
  final VideoData videoData;

  const VideoDetailPage({Key? key, required this.videoData}) : super(key: key);

  @override
  _VideoDetailPageState createState() => _VideoDetailPageState();
}

class _VideoDetailPageState extends State<VideoDetailPage>
    with SingleTickerProviderStateMixin {
  bool _foldSynopsis = true;
  late PaletteGenerator _paletteGenerator;

  Color _backgroundColorLight = Color(0xff16394d);
  Color _backgroundColorDark = Color(0xff182c3b);

  double get screenH => MediaQuery.of(context).size.height;

  @override
  void initState() {
    super.initState();
    getPaletteColor();
  }

  void getPaletteColor() async {
    try {
      var cacheFile = await Application.cacheManager
          .getFileFromCache(widget.videoData.posterBig ?? "");
      _paletteGenerator = await PaletteGenerator.fromImageProvider(
          Image.file(cacheFile!.file).image);
    } catch (e) {
      print("$e");
    } finally {
      if (_paletteGenerator.dominantColor != null) {
        _backgroundColorLight =
            _paletteGenerator.dominantColor!.color.withOpacity(0.5);
        _backgroundColorDark = _paletteGenerator.dominantColor!.color;
      }
      setState(() {});
    }
  }

  void toggleSynopsis() {
    setState(() {
      _foldSynopsis = !_foldSynopsis;
    });
  }

  bool get foldSynopsis => _foldSynopsis;

  @override
  Widget build(BuildContext context) {
    print("_VideoDetailPageState build");
    return Scaffold(
      appBar: AppBar(
        backgroundColor: _backgroundColorLight,
        title: Text("电影"),
        centerTitle: true,
      ),
      backgroundColor: _backgroundColorLight,
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 10),
          child: Column(
            children: <Widget>[
              _buildHeader(),
              _buildRating(),
              _buildSynopsis(),
              _buildActors(),
              _buildTrailer(),
              _buildBriefComments(),
            ],
          ),
        ),
      ),
      // bottomSheet: Column(
      //   children: [
      //     Container(
      //       height: 100,
      //       color: Colors.indigo,
      //     ),
      //     Container(
      //       height: 200,
      //       color: Colors.blueAccent,
      //     ),
      //   ],
      // ),
    );
  }

  Widget _buildHeader() {
    VideoData videoData = widget.videoData;
    return Container(
      height: 150,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(right: 5),
            child: CachedImageWidget(
              imageUrl: videoData.posterBig ?? "",
              fit: BoxFit.fitWidth,
            ),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Expanded(
                  child: Container(
                    child: Text(
                      videoData.title ?? "",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 30,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ),
                Container(
                  child: Row(
                    children: <Widget>[
                      Text(
                        "${videoData.year}",
                        style: TextStyle(
                          color: Colors.white54,
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 5),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.white54, width: 3),
                          shape: BoxShape.circle,
                        ),
                      ),
                      Text(
                        "${videoData.runtime} 分钟",
                        style: TextStyle(
                          color: Colors.white54,
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  child: Text(
                    "${videoData.genres?.join("/")}",
                    style: TextStyle(
                      color: Colors.white54,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Container(
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      Expanded(
                        child: IconTextButton(
                          icon: Icon(
                            Icons.favorite_border,
                            color: Color(0xfffcac2f),
                            size: 15,
                          ),
                          text: Text('想看'),
                          onPressed: () {},
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Expanded(
                        child: IconTextButton(
                          icon: Icon(
                            FontAwesomeIcons.star,
                            color: Color(0xfffcac2f),
                            size: 15,
                          ),
                          text: Text('看过'),
                          onPressed: () {},
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRating() {
    VideoData videoData = widget.videoData;
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      constraints: BoxConstraints.tightForFinite(height: 150.0),
      decoration: BoxDecoration(
        color: _backgroundColorDark,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Text(
                  "评分™",
                  style: TextStyle(color: Colors.white),
                ),
                Spacer(),
                Icon(Icons.keyboard_arrow_right, color: Colors.white30)
              ],
            ),
            Container(
              constraints: BoxConstraints.tightForFinite(height: 90),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          "${videoData.rating}",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 30,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        RatingStarWidget(
                          percentage: (videoData.rating! * 10).toInt(),
                        )
                      ],
                    ),
                  ),
                  RatingChartWidget(chartDatas: [40, 20, 10, 30, 0]),
                ],
              ),
            ),
            Divider(
              height: 1,
              color: Colors.white30,
            ),
            Container(
              padding: EdgeInsets.only(top: 5),
              child: Row(
                children: <Widget>[
                  Spacer(),
                  Text(
                    "${1}人看过 ${1}人想看",
                    style: TextStyle(
                      color: Colors.white70,
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSynopsis() {
    VideoData videoData = widget.videoData;
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            padding: EdgeInsets.symmetric(vertical: 5),
            child: Text(
              "剧情简介",
              style: TextStyle(
                color: Colors.white,
                fontSize: 15,
              ),
            ),
          ),
          GestureDetector(
            child: Text(
              videoData.description ?? "",
              style: TextStyle(
                color: Colors.white,
              ),
              maxLines: foldSynopsis ? 4 : 999,
              overflow: TextOverflow.ellipsis,
            ),
            onTap: () {
              toggleSynopsis();
            },
          ),
        ],
      ),
    );
  }

  Widget _buildActors() {
    const List<Map<String, dynamic>> actors = [
      {"name": "西蒙·金伯格", "role": "导演", "photo": ""},
      {"name": "苏菲·特纳", "role": "凤凰/琴·格蕾", "photo": ""},
      {"name": "詹姆斯·麦卡沃伊", "role": "X教授/查尔斯", "photo": ""},
      {"name": "迈克尔·法斯宾德", "role": "万磁王/埃瑞克·兰谢尔", "photo": ""},
      {"name": "尼古拉斯·霍尔特", "role": "野兽汉克/麦考伊", "photo": ""},
      {"name": "泰伊·谢里丹", "role": "镭射眼 Scott Summers", "photo": ""},
      {"name": "杰西卡·查斯坦", "role": "沃克 Vuk", "photo": ""},
      {"name": "詹妮弗·劳伦斯", "role": "魔形女/瑞雯", "photo": ""},
    ];

    return Container(
      margin: EdgeInsets.symmetric(vertical: 20),
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(bottom: 5),
            child: Row(
              children: <Widget>[
                Text(
                  "演职员",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                  ),
                ),
                Spacer(),
                Text(
                  "全部 38",
                  style: TextStyle(
                    color: Colors.white54,
                    fontSize: 12,
                  ),
                ),
                Icon(Icons.keyboard_arrow_right, color: Colors.white30),
              ],
            ),
          ),
          Container(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: actors.map((e) {
                  return Container(
                    width: 100,
                    margin: EdgeInsets.only(right: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(bottom: 5),
                          child: CachedImageWidget(
                            imageUrl: "https://via.placeholder.com/100x150",
                            fit: BoxFit.contain,
                          ),
                        ),
                        Text(
                          e["name"],
                          style: TextStyle(color: Colors.white),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          e["role"],
                          style: TextStyle(color: Colors.white54, fontSize: 12),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTrailer() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 20),
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(bottom: 5),
            child: Row(
              children: <Widget>[
                Text(
                  "预告片 / 剧照",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                  ),
                ),
                Spacer(),
                Text(
                  "全部 694",
                  style: TextStyle(
                    color: Colors.white54,
                    fontSize: 12,
                  ),
                ),
                Icon(Icons.keyboard_arrow_right, color: Colors.white30),
              ],
            ),
          ),
          Container(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: List.generate(
                  4,
                  (index) {
                    return Container(
                      width: 180,
                      margin: EdgeInsets.only(right: 1),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            child: CachedImageWidget(
                              imageUrl: "https://via.placeholder.com/180x120",
                              fit: BoxFit.contain,
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBriefComments() {
    const List<Map<String, dynamic>> comments = [
      {
        "avatar": "",
        "nickname": "掉线",
        "score": 10,
        "date": "",
        "contents": "【C-】负分剧本，智商全员下线，智者教授变圣母，",
        "like": 2010,
      },
      {
        "avatar": "",
        "nickname": "凌睿",
        "score": 10,
        "date": "",
        "contents": "不再是布莱恩辛格指导，质量明显下滑。",
        "like": 1810,
      },
      {
        "avatar": "",
        "nickname": "突然粉碎",
        "score": 10,
        "date": "",
        "contents": "我的妈呀老万求婚了，份子钱我先出了大家随意，",
        "like": 1750,
      },
      {
        "avatar": "",
        "nickname": "咆哮的小清新__",
        "score": 10,
        "date": "",
        "contents": "#X战警：黑凤凰#烂番茄新鲜度16%，",
        "like": 479,
      },
    ];

    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: _backgroundColorDark,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(bottom: 5),
            child: Row(
              children: <Widget>[
                Text(
                  "短评",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                  ),
                ),
                Spacer(),
                Text(
                  "全部短评 30617",
                  style: TextStyle(
                    color: Colors.white54,
                    fontSize: 12,
                  ),
                ),
                Icon(Icons.keyboard_arrow_right, color: Colors.white30),
              ],
            ),
          ),
          Column(
            children: comments.map((e) {
              return Container(
                margin: EdgeInsets.symmetric(vertical: 10),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: Colors.white12,
                    ),
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      child: Row(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.only(right: 10),
                            child: CircleAvatar(
                              radius: 15.0,
                              backgroundColor: ColorUtil.random(),
                            ),
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.only(bottom: 2),
                                child: Text(
                                  e["nickname"],
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                              RatingStarWidget(
                                percentage: e["score"],
                                starSize: 10,
                              )
                            ],
                          ),
                          Spacer(),
                          GestureDetector(
                            child: Icon(
                              Icons.more_horiz,
                              color: Colors.white,
                            ),
                            onTap: () {},
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.symmetric(vertical: 10),
                      child: Text(
                        e["contents"],
                        style: TextStyle(
                          color: Colors.white,
                        ),
                        maxLines: 6,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Container(
                        margin: EdgeInsets.only(left: 10, bottom: 15),
                        child: Row(
                          children: <Widget>[
                            Icon(
                              FontAwesomeIcons.thumbsUp,
                              color: Colors.white54,
                              size: 15,
                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 5, left: 2),
                              child: Text(
                                e["like"] < 1000
                                    ? "${e["like"]}"
                                    : "${(e["like"] / 1000).toStringAsFixed(1)}k",
                                style: TextStyle(
                                  color: Colors.white54,
                                  fontSize: 10,
                                ),
                              ),
                            ),
                          ],
                        )),
                  ],
                ),
              );
            }).toList(),
          ),
          Container(
            margin: EdgeInsets.only(top: 5),
            child: Row(
              children: <Widget>[
                Text(
                  "查看全部短评",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                  ),
                ),
                Spacer(),
                Icon(Icons.keyboard_arrow_right, color: Colors.white30),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
